/*
 * Copyright (c) 2019-2020, https://api.iot.10086.cn/(https://gitee.com/cmcc-iot-api/iot-card-open-application/).
 */
package cn.iot.card.open.sim.controller;

import cn.iot.card.open.constants.Constants;
import cn.iot.card.open.constants.ErrorCode;
import cn.iot.card.open.context.LoginContextHolder;
import cn.iot.card.open.context.model.LoginUser;
import cn.iot.card.open.ec.service.EcBlocSynService;
import cn.iot.card.open.exception.enums.BizExceptionEnum;
import cn.iot.card.open.modular.entity.AccountCard;
import cn.iot.card.open.modular.entity.Card;
import cn.iot.card.open.modular.entity.UserGroupRl;
import cn.iot.card.open.modular.log.ApiBussinessLog;
import cn.iot.card.open.modular.service.AccountCardService;
import cn.iot.card.open.modular.service.CardService;
import cn.iot.card.open.modular.service.UserService;
import cn.iot.card.open.pojo.page.LayuiPageFactory;
import cn.iot.card.open.pojo.page.LayuiPageInfo;
import cn.iot.card.open.sim.dto.general.ChangeSimStatusDTO;
import cn.iot.card.open.sim.dto.general.SimParamNodeDTO;
import cn.iot.card.open.sim.service.GeneralService;
import cn.iot.card.open.util.CommonUtil;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物联卡综合信息菜单
 *
 * @author 何光鑫
 * @date 20200310 16:47:06
 * @modify 20200310 何光鑫 v1.1.2 创建
 * @since v1.1.2
 */
@Controller
@RequestMapping("/general")
public class GeneralController extends BaseController {

    /**
     * 物联卡综合信息页面路径前缀
     */
    private static String PREFIX = "/modular/sim/general/";

    @Autowired
    private GeneralService generalService;

    @Autowired
    private CardService cardService;

    @Autowired
    private UserService userService;

    @Autowired
    private EcBlocSynService ecBlocSynService;

    @Autowired
    private AccountCardService accountCardService;

    /**
     * 跳转到物联卡综合信息页面
     *
     * @return 返回 string
     * @author 何光鑫
     * @date 20200310 16:47:06
     * @modify 20200310 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "general.html";
    }


    /**
     * 获取物联卡综合信息列表
     *
     * @param msisdn 物联卡号码
     * @param iccid 集成电路卡识别码
     * @param imsi 国际移动用户识别码
     * @return 返回 object
     * @throws IOException
     * @author 何光鑫
     * @date 20200310 16:51:41
     * @modify 20200310 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String msisdn,@RequestParam(required = false) String iccid,@RequestParam(required = false) String imsi) throws IOException {
        Map<String, Object> map = new HashMap<>();
        String cardType = "";
        String cardTypes="";
        String cardNum = "";
        if(ToolUtil.isNotEmpty(msisdn)){
            map.put(Constants.REQUEST_PARAM_MSISDN,msisdn);
            cardType = Constants.REQUEST_PARAM_MSISDN;
            cardTypes = Constants.REQUEST_PARAM_MSISDNS;
            cardNum = msisdn;
        }else if(ToolUtil.isNotEmpty(iccid)){
            map.put(Constants.REQUEST_PARAM_ICCID,iccid);
            cardType = Constants.REQUEST_PARAM_ICCID;
            cardTypes = Constants.REQUEST_PARAM_ICCIDS;
            cardNum = iccid;
        }else if(ToolUtil.isNotEmpty(imsi)){
            map.put(Constants.REQUEST_PARAM_IMSI,imsi);
            cardType = Constants.REQUEST_PARAM_IMSI;
            cardTypes = Constants.REQUEST_PARAM_IMSIS;
            cardNum = imsi;
        }else{
            return LayuiPageFactory.createEmptyPageInfo();
        }
        map.put(Constants.RESPONSE_DELETED,Constants.RESPONSE_DELETED_FALSE);
        List<Card> cards = cardService.getBaseMapper().selectByMap(map);
        if(ToolUtil.isEmpty(cards)){
            return LayuiPageFactory.createBizExceptionMsg(BizExceptionEnum.CARD_NOT_EXIT_IN_SYSTEM);
        }
        Card card = cards.get(0);
        // 验证当前用户是否有卡权限
        LoginUser loginUser = LoginContextHolder.getContext().getUser();
        UserGroupRl userGroupRl = userService.getUserGroupRlByUserAndCard(loginUser.getId(), card.getCardId());
        if (null == userGroupRl) {
            return LayuiPageFactory.createBizExceptionMsg(BizExceptionEnum.CARD_NOT_BELONG_USER);
        }
        Map<String, Object> cardDtoMap = cardService.getCardInfo(card.getCardId());
        Object accountIdObj = cardDtoMap.get(Constants.REQUEST_ACCOUNT_ID);
        if (ToolUtil.isEmpty(accountIdObj)) {
            // 当前卡未绑定任何账户
            return LayuiPageFactory.cteateErrorMsg(ErrorCode.ERR11047);
        }
        String accountId = String.valueOf(accountIdObj);
        String transId = CommonUtil.generateTransId(String.valueOf(accountId));
        return generalService.selectAllBasicInfo(transId,accountId,cardType,cardTypes,cardNum);
    }


    /**
     * 跳转到归属群组信息页面
     *
     * @param accountId 集团id
     * @param cardType 卡号类型（msisdn、iccid、imsi一种）
     * @param cardNum 卡号（与类型对应）
     * @param model
     * @return 返回
     * @author 何光鑫
     * @date 20200313 10:56:30
     * @modify 20200313 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/general_group/{accountId}/{cardType}/{cardNum}")
    public String generalGroup(@PathVariable("accountId") String accountId,@PathVariable("cardType") String cardType,@PathVariable("cardNum") String cardNum, Model model) {
        if (ToolUtil.isEmpty(cardNum)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("cardType", cardType);
        model.addAttribute("cardNum",cardNum);
        model.addAttribute("accountId", accountId);
        return PREFIX + "general_group.html";
    }

    /**
     * 查询归属群组信息
     *
     * @param accountId 集团id
     * @param cardType 卡号类型（msisdn、iccid、imsi一种）
     * @param cardNum 卡号（与类型对应）
     * @return 返回
     * @throws IOException
     * @author 何光鑫
     * @date 20200313 10:56:30
     * @modify 20200313 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/generalGroup")
    @ResponseBody
    public LayuiPageInfo getGeneralGroup(@RequestParam String accountId, @RequestParam(required = false) String cardType,@RequestParam(required = false) String cardNum) throws IOException{
        if (ToolUtil.isEmpty(accountId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        String transId = CommonUtil.generateTransId(accountId);
        return generalService.queryGroupByMember(transId, accountId, cardType,cardNum);
    }

    /**
     * 跳转到物联卡余额信息页面
     *
     * @param accountId 集团id
     * @param cardType 卡号类型（msisdn、iccid、imsi一种）
     * @param cardNum 卡号（与类型对应）
     * @param model
     * @return 返回 string
     * @author 何光鑫
     * @date 20200313 10:56:30
     * @modify 20200313 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/general_balance/{accountId}/{cardType}/{cardNum}")
    public String generalBalance(@PathVariable("accountId") String accountId,@PathVariable("cardType") String cardType,@PathVariable("cardNum") String cardNum, Model model) {
        if (ToolUtil.isEmpty(cardNum)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("cardType", cardType);
        model.addAttribute("cardNum",cardNum);
        model.addAttribute("accountId", accountId);
        return PREFIX + "general_balance.html";
    }

    /**
     * 查询物联卡余额
     *
     * @param accountId 集团id
     * @param cardType 卡号类型（msisdn、iccid、imsi一种）
     * @param cardNum 卡号（与类型对应）
     * @return 返回 general group
     * @throws IOException
     * @author 何光鑫
     * @date 20200313 10:56:30
     * @modify 20200313 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/generalBalance")
    @ResponseBody
    public LayuiPageInfo getGeneralBalance(@RequestParam String accountId, @RequestParam(required = false) String cardType,@RequestParam(required = false) String cardNum) throws IOException{
        if (ToolUtil.isEmpty(accountId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        String transId = CommonUtil.generateTransId(accountId);
        List<Map<String, Object>> result = new ArrayList<>();
        Map<String, Object> balanceInfo = generalService.queryBalanceInfo(transId, accountId, cardType, cardNum);
        result.add(balanceInfo);
        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setData(result);
        layuiPageInfo.setCount(result.size());
        return layuiPageInfo;
    }

    /**
     * 跳转到物联卡已订购资费页面
     *
     * @param accountId 集团id
     * @param cardType 卡号类型（msisdn、iccid、imsi一种）
     * @param cardNum 卡号（与类型对应）
     * @param model
     * @return 返回 string
     * @author 何光鑫
     * @date 20200313 10:56:30
     * @modify 20200313 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/ordered_charges/{accountId}/{cardType}/{cardNum}")
    public String blocOrderCharges(@PathVariable("accountId") String accountId, @PathVariable("cardType") String cardType,@PathVariable("cardNum") String cardNum,Model model) {
        if (ToolUtil.isEmpty(accountId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("cardType", cardType);
        model.addAttribute("cardNum",cardNum);
        model.addAttribute("accountId", accountId);
        return PREFIX + "general_orderedCharges.html";
    }

    /**
     * 查询物联卡已订购资费
     *
     * @param accountId 集团id
     * @param cardType 卡号类型（msisdn、iccid、imsi一种）
     * @param cardNum 卡号（与类型对应）
     * @return 返回 bloc order charges
     * @throws IOException
     * @author 何光鑫
     * @date 20200313 10:56:30
     * @modify 20200313 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/orderedCharges")
    @ResponseBody
    public LayuiPageInfo getBlocOrderCharges(@RequestParam String accountId,@RequestParam String cardType,@RequestParam String cardNum) throws IOException{
        if (ToolUtil.isEmpty(accountId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        String transId = CommonUtil.generateTransId(accountId);
        Map<String, String> parameterMap = new HashMap<>();
        parameterMap.put(Constants.REQUEST_QUERY_TYPE, Constants.REQUEST_QUERY_TYPE_SIM);
        //如果卡号类型不是msisdn，查出msisdn再调用接口
        if(cardType.equals(Constants.REQUEST_PARAM_MSISDN)) {
            parameterMap.put(cardType, cardNum);
        }else{
            Map<String, Object> basicInfoMap = generalService.queryBasicInfo(transId, accountId, cardType, cardNum);
            if(ToolUtil.isEmpty(basicInfoMap)){
                return LayuiPageFactory.cteateErrorMsg(ErrorCode.ERR11011);
            }
            if(ToolUtil.isNotEmpty(basicInfoMap.get(Constants.RESPONSE_ERROR))){
                return LayuiPageFactory.cteateErrorMsg(ErrorCode.ERR11011);
            }else{
                cardNum = (String)basicInfoMap.get(Constants.REQUEST_PARAM_MSISDN);
                parameterMap.put(Constants.REQUEST_PARAM_MSISDN, cardNum);
            }
        }
        return ecBlocSynService.queryOrderCharges(transId, accountId,parameterMap);
    }

    /**
     * 跳转到查看可变更资费页面
     *
     * @param accountId 集团id
     * @param cardType 卡号类型（msisdn、iccid、imsi一种）
     * @param cardNum 卡号（与类型对应）
     * @param offeringId 资费id
     * @param model
     * @return 返回 string
     * @author 何光鑫
     * @date 20200313 14:36:01
     * @modify 20200313 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/changeable_charges/{accountId}/{cardType}/{cardNum}/{offeringId}")
    public String changeAbleCharges(@PathVariable("accountId") String accountId, @PathVariable("cardType") String cardType,@PathVariable("cardNum") String cardNum,
                                    @PathVariable("offeringId") String offeringId,Model model) {
        if (ToolUtil.isEmpty(accountId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("accountId", accountId);
        model.addAttribute("cardType", cardType);
        model.addAttribute("cardNum",cardNum);
        model.addAttribute("offeringId", offeringId);
        return PREFIX + "general_changeCharges.html";
    }

    /**
     * 查看物联卡可变更资费
     *
     * @param accountId 集团id
     * @param cardType 卡号类型（msisdn、iccid、imsi一种）
     * @param cardNum 卡号（与类型对应）
     * @param offeringId 资费id
     * @return 返回 changeable charges
     * @throws IOException 描述抛出异常原因
     * @author 何光鑫
     * @date 20200313 14:38:06
     * @modify 20200313 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/changeableCharges")
    @ResponseBody
    public LayuiPageInfo getChangeableCharges(@RequestParam String accountId,@RequestParam String cardType,@RequestParam String cardNum,@RequestParam String offeringId) throws IOException{
        if (ToolUtil.isEmpty(accountId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        String transId = CommonUtil.generateTransId(accountId);
        Map<String, String> parameterMap = new HashMap<>();
        parameterMap.put(Constants.REQUEST_QUERY_TYPE, "2");
        parameterMap.put(Constants.REQUEST_PARAM_DESCOFFERINGID, offeringId);
        //如果卡号类型不是msisdn，查出msisdn再调用接口
        if(cardType.equals(Constants.REQUEST_PARAM_MSISDN)) {
            parameterMap.put(cardType, cardNum);
        }else{
            Map<String, Object> basicInfoMap = generalService.queryBasicInfo(transId, accountId, cardType, cardNum);
            if(ToolUtil.isEmpty(basicInfoMap)){
                return LayuiPageFactory.cteateErrorMsg(ErrorCode.ERR11011);
            }
            if(ToolUtil.isNotEmpty(basicInfoMap.get(Constants.RESPONSE_ERROR))){
                return LayuiPageFactory.cteateErrorMsg(ErrorCode.ERR11011);
            }else{
                cardNum = (String)basicInfoMap.get(Constants.REQUEST_PARAM_MSISDN);
                parameterMap.put(Constants.REQUEST_PARAM_MSISDN, cardNum);
            }
        }
        return generalService.queryChangeableOfferings(transId, accountId,parameterMap);
    }


    /**
     * 跳转到物联卡状态变更页面
     *
     * @param accountId 集团id
     * @param model
     * @return 返回 string
     * @author 何光鑫
     * @date 20200315 13:29:50
     * @modify 20200315 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/changeable_status/{accountId}")
    public String changeAbleStatus(@PathVariable("accountId") String accountId,Model model) {
        if (ToolUtil.isEmpty(accountId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("accountId", accountId);
        return PREFIX + "general_changeStatus.html";
    }


    /**
     * 调用API接口实现物联卡状态变更
     *
     * @param changeSimStatusDTO 物联卡状态变更请求对象
     * @return 返回 response data
     * @throws IOException
     * @author 何光鑫
     * @date 20200315 13:30:30
     * @modify 20200315 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/changeStatus")
    @ApiBussinessLog(value = "物联卡状态变更")
    @ResponseBody
    public ResponseData changeStatus(ChangeSimStatusDTO changeSimStatusDTO) throws IOException{
        String cardType = changeSimStatusDTO.getCardType();
        String cardNum = changeSimStatusDTO.getCardNum();
        String operType = changeSimStatusDTO.getOperType();
        Card card = cardService.findCard(cardType, cardNum);
        if (null == card) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_EXIT_IN_SYSTEM);
        }
        LoginUser loginUser =  LoginContextHolder.getContext().getUser();
        UserGroupRl userGroupRl = userService.getUserGroupRlByUserAndCard(loginUser.getId(), card.getCardId());
        if (null == userGroupRl) {
            throw new ServiceException(Integer.valueOf(BizExceptionEnum.CARD_NOT_BELONG_USER.getCode()),BizExceptionEnum.CARD_NOT_BELONG_USER.getMessage());
        }

        AccountCard accountCard = accountCardService.getBaseMapper().findByCardId(card.getCardId());
        String accountId = String.valueOf(accountCard.getAccountId());
        String transId = CommonUtil.generateTransId(accountId);
        Map<String, String> parameterMap = new HashMap<>();
        parameterMap.put(Constants.REQUEST_PARAM_OPERTYPE, operType);
        parameterMap.put(cardType, cardNum);
        return generalService.changeSimStatus(transId, accountId, parameterMap);
    }

    /**
     * 跳转到物联卡状态变更历史界面
     *
     * @param accountId 集团id
     * @param cardType 卡号类型（msisdn、iccid、imsi一种）
     * @param cardNum 卡号（与类型对应）
     * @param model
     * @return 返回 string
     * @author 何光鑫
     * @date 20200316 09:02:24
     * @modify 20200316 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/history_status/{accountId}/{cardType}/{cardNum}")
    public String historyStatus(@PathVariable("accountId") String accountId,@PathVariable("cardType") String cardType,@PathVariable("cardNum") String cardNum, Model model) {
        if (ToolUtil.isEmpty(cardNum)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("cardType", cardType);
        model.addAttribute("cardNum",cardNum);
        model.addAttribute("accountId", accountId);
        return PREFIX + "general_historyStatus.html";
    }


    /**
     * 调用api接口查询物联卡状态变更历史
     *
     * @param accountId 集团id
     * @param cardType 卡号类型（msisdn、iccid、imsi一种）
     * @param cardNum 卡号（与类型对应）
     * @return 返回 history status
     * @throws IOException
     * @author 何光鑫
     * @date 20200316 09:02:54
     * @modify 20200316 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/historyStatus")
    @ResponseBody
    public LayuiPageInfo getHistoryStatus(@RequestParam String accountId, @RequestParam(required = false) String cardType,@RequestParam(required = false) String cardNum) throws IOException{
        if (ToolUtil.isEmpty(accountId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Map<String, String> parameterMap = new HashMap<>();
        parameterMap.put(cardType,cardNum);
        String transId = CommonUtil.generateTransId(accountId);
        return generalService.querySimChangeHistory(transId, accountId, parameterMap);
    }

    /**
     * 跳转到节电参数变更页面
     *
     * @param accountId 集团id
     * @param model
     * @return 返回 string
     * @author 何光鑫
     * @date 20200316 10:48:58
     * @modify 20200316 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/change_paramNode/{accountId}")
    public String paramNode(@PathVariable("accountId") String accountId,Model model) {
        if (ToolUtil.isEmpty(accountId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("accountId", accountId);
        return PREFIX + "general_paramNode.html";
    }


    /**
     * 调用api接口实现物联卡节电参数变更
     *
     * @param simParamNodeDTO 物联卡节电参数变更请求参数
     * @return 返回 response data
     * @throws IOException
     * @author 何光鑫
     * @date 20200316 10:49:43
     * @modify 20200316 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    @RequestMapping("/changeParamNode")
    @ApiBussinessLog(value = "物联卡节电参数变更")
    @ResponseBody
    public ResponseData changeParamNode(SimParamNodeDTO simParamNodeDTO) throws IOException{
        String msisdn = simParamNodeDTO.getMsisdn();
        Card card = cardService.findCard(Constants.REQUEST_PARAM_MSISDN, msisdn);
        if (null == card) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_EXIT_IN_SYSTEM);
        }
        LoginUser loginUser =  LoginContextHolder.getContext().getUser();
        UserGroupRl userGroupRl = userService.getUserGroupRlByUserAndCard(loginUser.getId(), card.getCardId());
        if (null == userGroupRl) {
            throw new ServiceException(Integer.valueOf(BizExceptionEnum.CARD_NOT_BELONG_USER.getCode()),BizExceptionEnum.CARD_NOT_BELONG_USER.getMessage());
        }

        AccountCard accountCard = accountCardService.getBaseMapper().findByCardId(card.getCardId());
        String accountId = String.valueOf(accountCard.getAccountId());
        String transId = CommonUtil.generateTransId(accountId);
        String apnName = simParamNodeDTO.getApnName();
        String precisionType = simParamNodeDTO.getPrecisionType();
        String precisionVal = simParamNodeDTO.getPrecisionVal();
        return generalService.changeParamNode(transId, accountId, msisdn,apnName,precisionType,precisionVal);
    }
}
